package com.chuangke.flowable.listener;

import java.io.Serial;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import org.apache.commons.beanutils.MethodUtils;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.engine.impl.el.FixedValue;
import org.springframework.stereotype.Component;

import com.chuangke.common.exception.ChuangkeException;
import com.chuangke.common.utils.SpringContextUtil;
import com.chuangke.flowable.constant.Consts;

@Component
public class EndExecutionListener implements ExecutionListener {

	
    private static final long serialVersionUID = 1L;

	private FixedValue service;

	@Override
	public void notify(DelegateExecution execution) {
		Object obj = null;
		try {
			obj = SpringContextUtil.getBean(Class.forName(service.getExpressionText()));
			String audit = (String) execution.getVariable("audit");
			String businessKey = (String) execution.getVariable("businessKey");
			Map<String, Object> varMap = execution.getVariables();

			if (Consts.VAR_AUDIT_OPT_AGREE.equals(audit)) {
				MethodUtils.invokeMethod(obj, "complete", new Object[] { businessKey, varMap });
			}
		} catch (InvocationTargetException e) {
			if(e.getCause() instanceof ChuangkeException) {
				throw (ChuangkeException)e.getCause() ;
			}else {
				throw new RuntimeException(e); 
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
